package com.mobile.check.db;

import android.text.TextUtils;

import com.github.yuweiguocn.library.greendao.MigrationHelper;

import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.List;

import cn.droidlover.xdroidmvp.base.BaseApplication;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import com.mobile.check.beans.CheckFileInfo;
import com.mobile.check.beans.CheckItemInfo;
import com.mobile.check.beans.TaskInfo;
import com.mobile.check.beans.TaskItemInfo;

public class EntityManager {

    private static EntityManager entityManager;
    DaoSession mDaoSession;
    TaskInfoDao taskInfoDao;
    TaskItemInfoDao taskItemInfoDao;
    CheckItemInfoDao checkItemInfoDao;
    CheckFileInfoDao checkFileInfoDao;

    public EntityManager() {
        DaoMaster.OpenHelper devOpenHelper = new DaoMaster.OpenHelper(BaseApplication.getContext(), "collect-db", null) {
            @Override
            public void onUpgrade(Database db, int oldVersion, int newVersion) {
                //把需要管理的数据库表DAO作为最后一个参数传入到方法中
                MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
                    @Override
                    public void onCreateAllTables(Database db, boolean ifNotExists) {
                        DaoMaster.createAllTables(db, ifNotExists);
                    }

                    @Override
                    public void onDropAllTables(Database db, boolean ifExists) {
                        DaoMaster.dropAllTables(db, ifExists);
                    }
                }, TaskInfoDao.class, TaskItemInfoDao.class, CheckItemInfoDao.class);
            }
        };
        DaoMaster mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
        taskInfoDao = mDaoSession.getTaskInfoDao();
        taskItemInfoDao = mDaoSession.getTaskItemInfoDao();
        checkFileInfoDao = mDaoSession.getCheckFileInfoDao();
        checkItemInfoDao = mDaoSession.getCheckItemInfoDao();
    }

    /**
     * 创建单例
     *
     * @return
     */
    public static EntityManager getInstance() {
        if (entityManager == null) {
            entityManager = new EntityManager();
        }
        return entityManager;
    }

    public Long saveTaskInfo(TaskInfo info) {
        return taskInfoDao.insertOrReplace(info);
    }


    public void saveTaskInfo(List<TaskInfo> list) {
        taskInfoDao.insertOrReplaceInTx(list);
    }

    public void delTaskInfo(List<TaskInfo> list) {
        taskInfoDao.deleteInTx(list);
    }

    public void delTaskInfo(TaskInfo taskInfo) {
        taskInfoDao.delete(taskInfo);
        delTaskItemInfoByParentId(taskInfo.get_ID());
    }

    public void uploadTaskInfo(TaskInfo info) {
        taskInfoDao.update(info);
    }

    public TaskInfo queryDeviceInfoById(Long _ID) {
        mDaoSession.clear();
        return taskInfoDao.queryBuilder().where(TaskInfoDao.Properties._ID.eq(_ID)).unique();
    }


    public List<TaskInfo> queryTaskInfo() {
        mDaoSession.clear();
        return taskInfoDao.queryBuilder().list();
    }

    public List<TaskInfo> queryTaskInfo(int taskType) {
        mDaoSession.clear();
        return taskInfoDao.queryBuilder().where(TaskInfoDao.Properties.TaskType.eq(taskType), TaskInfoDao.Properties.HadDowned.eq(true)).list();
    }

    public List<TaskInfo> queryTaskInfo(int taskType, boolean isLocal) {
        mDaoSession.clear();
        return taskInfoDao.queryBuilder().where(TaskInfoDao.Properties.TaskType.eq(taskType), TaskInfoDao.Properties.IsLocalFile.eq(false)).list();
    }

    public int queryTaskInfoCount(String name, int taskType) {
        mDaoSession.clear();
        return taskInfoDao.queryBuilder().where(TaskInfoDao.Properties.Task_name.eq(name), TaskInfoDao.Properties.TaskType.eq(taskType)).list().size();
    }

    public TaskInfo queryTaskInfoCount(String name, int taskType, boolean isLocal) {
        NLog.d("EntityManger", "name = " + name + " taskType=" + taskType + " isLocal=" + isLocal);
        mDaoSession.clear();
        List<TaskInfo> list = taskInfoDao.queryBuilder().where(TaskInfoDao.Properties.Task_name.eq(name), TaskInfoDao.Properties.TaskType.eq(taskType), TaskInfoDao.Properties.IsLocalFile.eq(isLocal)).list();
        if (list.size() != 0) {
            return list.get(0);
        } else {
            return null;
        }
    }


    public Long saveTaskItemInfo(TaskItemInfo info) {
        return taskItemInfoDao.insertOrReplace(info);
    }

    public void saveTaskItemInfo(List<TaskItemInfo> list) {
        taskItemInfoDao.insertOrReplaceInTx(list);
    }

    public void saveCheckItemInfo(List<CheckItemInfo> list) {
        checkItemInfoDao.insertOrReplaceInTx(list);
    }

    public void clearCheckItemInfos() {
        checkItemInfoDao.deleteAll();
    }

    public void clearCheckItemInfos(String xlsxName) {
        List<CheckItemInfo> list = checkItemInfoDao.queryBuilder().where(CheckItemInfoDao.Properties.BelongFileName.eq(xlsxName)).list();
        checkItemInfoDao.deleteInTx(list);
    }



    public List<CheckItemInfo> queryCheckItemByCode(String code) {
        String ss = code.replace("-", "");

        WhereCondition orWhereCondition =  checkItemInfoDao.queryBuilder().or(CheckItemInfoDao.Properties.ErCode.eq(code), CheckItemInfoDao.Properties.ErCode.eq(ss));
        List<CheckItemInfo> list =  checkItemInfoDao.queryBuilder().where(CheckItemInfoDao.Properties.BelongFileName.isNotNull(),orWhereCondition).list();
        return list;
    }

    public CheckItemInfo getScanResultByID(long key) {
        List<CheckItemInfo> list = checkItemInfoDao.queryBuilder().where(CheckItemInfoDao.Properties._ID.eq(key)).list();
        return list.get(0);
    }


    public void delCheckFile(String xlsxFilePath) {
        List<CheckFileInfo> list = checkFileInfoDao.queryBuilder().where(CheckFileInfoDao.Properties.XlsxPath.eq(xlsxFilePath),CheckFileInfoDao.Properties.XlsxName.isNotNull()).list();
        for (CheckFileInfo checkFileInfo : list) {
            clearCheckItemInfos(checkFileInfo.getXlsxName());
        }
        checkFileInfoDao.deleteInTx(list);
    }

    public void delCheckFileInfo() {
        List<CheckFileInfo> list = checkFileInfoDao.queryBuilder().where(CheckFileInfoDao.Properties.XlsxName.isNotNull()).list();
        for (CheckFileInfo checkFileInfo : list) {
            clearCheckItemInfos(checkFileInfo.getXlsxName());
        }
        checkFileInfoDao.deleteInTx(list);
    }

    public long saveCheckFIle(CheckFileInfo checkFileInfo) {
        return checkFileInfoDao.insertOrReplace(checkFileInfo);
    }


    public CheckFileInfo queryCheckFileByName(String filename) {
        List<CheckFileInfo> list = checkFileInfoDao.queryBuilder().where(CheckFileInfoDao.Properties.XlsxName.eq(filename)).list();
        return list.size() > 0 ? list.get(0) : null;
    }

    public List<CheckFileInfo> queryCheckFiles() {
        List<CheckFileInfo> list = checkFileInfoDao.queryBuilder().list();
        return list;
    }


    public void delTaskItemInfo(List<TaskItemInfo> list) {
        if (!Kits.Empty.check(list)) {
            taskItemInfoDao.deleteInTx(list);
        }
    }
    public void delTaskItemInfo(TaskItemInfo taskItemInfo) {
        taskItemInfoDao.delete(taskItemInfo);
    }

    public void delTaskItemInfoByParentId(Long parentID) {
        List<TaskItemInfo> list = queryTaskItemInfoByParentId(parentID);
        delTaskItemInfo(list);
    }


    public void uploadTaskItemInfo(TaskItemInfo info) {
        taskItemInfoDao.update(info);
    }

    public TaskItemInfo queryTaskItemInfoById(Long _ID) {
        mDaoSession.clear();
        return taskItemInfoDao.queryBuilder().where(TaskItemInfoDao.Properties._ID.eq(_ID)).unique();
    }


    public List<TaskItemInfo> queryTaskItemInfoByParentId(Long parentID) {
        mDaoSession.clear();
        return taskItemInfoDao.queryBuilder().where(TaskItemInfoDao.Properties.ParentId.eq(parentID)).orderAsc(TaskItemInfoDao.Properties.RowIndex).list();
    }

    public List<TaskItemInfo> queryTaskItemInfoByParentId(Long parentID, String searchContent) {
        if (TextUtils.isEmpty(searchContent)) {
            return queryTaskItemInfoByParentId(parentID);
        } else {
            mDaoSession.clear();
            return taskItemInfoDao.queryBuilder().where(TaskItemInfoDao.Properties.ParentId.eq(parentID),
                    TaskItemInfoDao.Properties.Label.like("%" + searchContent + "%")).list();
        }
    }
}
